<?php

namespace App\Http\Controllers\Company;

use App\Facades\Site;
use App\Facades\Style;
use App\Http\Controllers\Company\CommonController;
use App\Http\Requests\Company\Job\AddJobRequest;
use App\Http\Requests\Company\Job\UpdateJobRequest;
use App\Models\Admin\CompanyJobTemplate;
use App\Models\Common\CollTown;
use App\Models\Common\CollArea;
use App\Models\Common\CollPosition;
use App\Models\Company\CompanyBasic;
use App\Models\Company\CompanyContact;
use App\Models\Company\CompanyDepartment;
use App\Models\Company\CompanyJob;
use App\Models\Company\CompanyRefreshLog;
use App\Models\Company\Points;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class JobController extends CommonController{

    /**
     * 职位发布页
     * @param Request $request
     * @return mixed
     */
    public function publish(Request $request){
        $user = auth()->guard('company')->user();
        $companyDepartment = CompanyDepartment::where('uid', $user->uid)->get();
        $companyBasic = CompanyBasic::where('uid', $user->uid)->orderBy('updatetime', 'desc')->first();
        //企业不存在时
        if(empty($companyBasic)){
            return redirect("company/register_basic");
        }
        $companyBasic->cn_region = CollArea::getAreaName($companyBasic->region);
        //DB::enableQueryLog();
        //$sql=DB::getQueryLog();
        //print_r($sql);
        return Style::view('company.jobpublish', compact('companyDepartment', 'companyBasic'));
    }

    /**
     * 返回岗位模板信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */

    public function jobTemplate(Request $request){
        $jobArr = $request->job_opt;//获取所选模板
        $jobTotal = 5;//岗位最大模板总数
        $JobTemplateArr = [];
        $jobArrId = [];
        if(count($jobArr) > 0){
            //循环第一个最重要添加的模板信息
            foreach($jobArr as $v){
                if(count($JobTemplateArr) >= $jobTotal){
                    break;
                }
                $companyJobTemplate = CompanyJobTemplate::where('jobsort1', $v)->orderBy('updated_at', 'desc')->take(5)->get();
                if(count($companyJobTemplate) > 0){
                    foreach($companyJobTemplate as $vv){
                        if(count($JobTemplateArr) >= $jobTotal){
                            break;
                        }
                        $JobTemplateArr[] = $vv;
                        $jobArrId[] = $vv->id;
                    }
                }
            }
            //当信息内容少于5个时，添加备选内容
            if(count($JobTemplateArr) < 5){
                foreach($jobArr as $v){
                    if(count($JobTemplateArr) >= $jobTotal){
                        break;
                    }
                    $twoJobTemplate = CompanyJobTemplate::where(function($query) use ($v){
                        $query->orWhere('jobsort2', '=', $v)
                            ->orWhere('jobsort3', '=', $v)
                            ->orWhere('jobsort4', '=', $v)
                            ->orWhere('jobsort5', '=', $v);
                    })->where(function($query) use ($jobArrId){
                        $query->WhereNotIn('id', $jobArrId);
                    })->orderBy('updated_at', 'desc')->get();
                    //当总数满5个退出
                    if(count($twoJobTemplate) > 0 && $jobTotal - count($JobTemplateArr) > 0){
                        foreach($twoJobTemplate as $vvv){
                            if(count($JobTemplateArr) >= $jobTotal){
                                break;
                            }
                            $JobTemplateArr[] = $vvv;
                            $jobArrId[] = $vvv->id;
                        }
                    }
                }
            }
        }
        return response()->json(['status' => '0', 'JobTemplateInfo' => $JobTemplateArr]);
    }


    /**
     * 数据库添加职位
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(AddJobRequest $request){
        $user = auth()->guard('company')->user();
        if($user->postNumber() > 0){
            $input = $request->only('job_title', 'part_status', 'job_category1', 'job_category2', 'job_category3', 'job_category4', 'job_category5', 'industry', 'location1',
                'location2', 'location3', 'location4', 'location5', 'department', 'recruiting_num', 'salary_above', 'salary_below', 'description', 'education', 'work_year'
                , 'age_above', 'age_below', 'gender', 'language', 'welfare', 'contact_info', 'lang_type');

            $input['addtime'] = date('Y-m-d H:i:s', time());
            $input['updatetime'] = date('Y-m-d H:i:s', time());
            $input['uid'] = $user->uid;
            $input['lang_type'] = 'cn';
            $CompanyBasic = CompanyBasic::where('uid', $user->uid)->orderBy('updatetime', 'desc')->first();
            $input['com_id'] = $CompanyBasic->id;
            //审核状态设置
            switch(Site::get('job_review')){
                case  1:
                    $input['job_status'] = 1;
                    break;
                case  2:
                    $input['job_status'] = ($user->viptime >= date('Y-m-d H:i:s')) ? 1 : 0;
                    break;
                case  3:
                    $input['job_status'] = 0;
                    break;
                default:
                    $input['job_status'] = 0;
            }

            $companyJob = CompanyJob::create($input);
            if($request->contact_info == 2){
                $input = $request->only('contacts', 'mobile', 'phone', 'fax', 'email');
                $input['job_id'] = $companyJob->id;
                $input['uid'] = $user->uid;
                $input['addtime'] = date('Y-m-d H:i:s', time());
                $input['updatetime'] = date('Y-m-d H:i:s', time());
                CompanyContact::create($input);
            }
            $user->postDeduct(1);

            return redirect('company/jobadmin');
        }else{
            return back()->withInput()->with('info', "您的职位数已用完请先购买!");
        }
    }

    /**
     * 职位管理
     * @param Request $request
     * @return mixed
     */
    public function admin(Request $request){
        $user = auth()->guard('company')->user();
        //获取面试通知记录
        $joblist = DB::table('company_job as t1')
            ->join('company_basic as t2', 't1.com_id', '=', 't2.id')
            ->select(
                't1.id', 't1.updatetime', 't1.com_id', 't1.recruiting_num',
                't2.company_name', 't1.job_title', 't1.contact_info', 't1.salary_above', 't1.salary_below', 't1.job_status', 't1.urgent', 't1.lang_type'
            )
            ->where('t1.uid', $user->uid)
            ->where('t1.job_status', '!=', 4)
            ->where(function($query) use ($request){
                if(strlen($request->keyWord) > 0){
                    $query->where('t1.job_title', 'like', '%' . $request->keyWord . '%');
                }
            })
            ->where(function($query) use ($request){
                if(strlen($request->job_status) > 0){
                    $query->where('t1.job_status', $request->job_status);
                }
            })
            ->where('t1.lang_type', 'cn')
            ->orderBy('updatetime', 'desc')
            ->orderBy('id', 'desc')
            ->paginate(20);

        foreach($joblist as $v){
            if($v->urgent > date('Y-m-d H:i:s', strtotime('-5 day'))){
                $v->iurgent = 1;
            }else{
                $v->iurgent = 0;
            }
        }
        $job_status = $request->job_status;
        // dd($favorites);
        //设置状态
        //    $job_status =  ($this->job_status!='') ? $this->job_status : '';
        return Style::view('company.jobadmin', compact('joblist', 'job_status'));
    }

    /**
     * 设置状态
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function status(Request $request){
        $user = auth()->guard('company')->user();
        $allow = array(1, 2, 4); //允许的状态码
        if(in_array($request->status, $allow)){
            if(!empty($request->selected_id)){
                $companyJob = CompanyJob::select('id', 'job_status')->where('uid', $user->uid)->whereIn('id', $request->selected_id)->get();
                foreach($companyJob as $k => $v){
                    if(($v->job_status != 0 and $v->job_status != 4 and $v->job_status != 7) or $request->status == 4){
                        $input['job_status'] = $request->status;
                        $input['xs_status'] = 0;
                        CompanyJob::where('uid', $user->uid)->where('id', $v->id)->update($input);
                    }else{
                        return back()->withInput()->with('info', "操作失败，请联系网站客服");
                    }
                }
            }elseif(!empty($request->id)){
                $companyJob = CompanyJob::select('id', 'job_status')->where('uid', $user->uid)->where('id', $request->id)->first();
                if(($companyJob->job_status != 0 and $companyJob->job_status != 4 and $companyJob->job_status != 7) or $request->status == 4){
                    $companyJob->job_status = $request->status;
                    $companyJob->xs_status = 0;
                    $companyJob->save();
                }else{
                    return back()->withInput()->with('info', "操作失败，请联系网站客服");
                }
            }
            return back()->withInput();
        }else{
            return response('错误代码!', 404);
        }
    }

    /**
     * 刷新职位
     * @param Request $request
     * @return $this
     */
    public function refresh(Request $request){
        $user = auth()->guard('company')->user();

        if(CompanyRefreshLog::isRefresh()){//可以刷新
            if(!empty($request->selected_id)){
                $companyJob = CompanyJob::select('id', 'job_status')->where('uid', $user->uid)->whereIn('id', $request->selected_id)->get();
                foreach($companyJob as $k => $v){
                    $input['updatetime'] = date('Y-m-d H:i:s');
                    $input['xs_status'] = 0;
                    CompanyJob::where('uid', $user->uid)->where('id', $v->id)->update($input);
                }
            }elseif(!empty($request->id)){
                $companyJob = CompanyJob::select('id', 'job_status')->where('uid', $user->uid)->where('id', $request->id)->first();
                $companyJob->updatetime = date('Y-m-d H:i:s');
                $companyJob->xs_status = 0;
                $companyJob->save();
            }
            //插入刷新记录
            $CompanyRefreshLog = new CompanyRefreshLog();
            $CompanyRefreshLog->uid = $user->uid;
            $CompanyRefreshLog->refresh_time = date('Y-m-d H:i:s');
            $CompanyRefreshLog->save();

            if($request->ajax()){
                return response()->json(['status' => 200, 'message' => '刷新成功']);
            }else{
                return back()->withInput()->with('info', "刷新成功");
            }
        }else{
            return $this->refreshError($request);
        }
    }

    /**
     * 刷新错误提示信息
     * @param $max
     */
    protected function refreshError($request){
        if(CompanyRefreshLog::getMax() < 0){
            $infoTip = "您还是普通会员，请先开通vip后再刷新！";
        }else{
            $infoTip = "请明天再来刷新，vip每天最大刷新次数" . CompanyRefreshLog::getMax() . "次！";
        }

        if($request->ajax()){
            return response()->json(['error' => 504, 'message' => $infoTip]);
        }else{
            return back()->withInput()->with('error', $infoTip);
        }
    }

    /**
     * 职位加急
     * @param Request $request
     * @return $this|\Illuminate\Http\RedirectResponse
     */
    public function urgent(Request $request){
        $user = auth()->guard('company')->user();
        //获取积分剩余个数
        if($user->viptime > date('Y-m-d H:i:s', time())){//会员优先使用会员积分
            $integralv = $user->vip_integral;
            $feld = "vip_integral";
            if($integralv < 10){
                if($user->integral > $integralv){
                    $integralv = $user->integral;
                    $feld = "integral";
                }
            }
        }else{
            $integralv = $user->integral;
            $feld = "integral";
        }

        if($integralv < 10){
            if($request->ajax()){
                return response()->json(['status' => 601, 'message' => "加急失败,您的积分只有" . $integralv . "个!"]);
            }else{
                return back()->withInput()->with('info', "加急失败,您的积分只有" . $integralv . "个!");
            }
        }else{
            if(!empty($request->id)){
                $input['urgent'] = date('Y-m-d H:i:s', time());
                $input['xs_status'] = 0;
                CompanyJob::where('uid', $user->uid)->where('id', $request->id)->update($input);
                $user->{$feld} = $integralv - 10;
                $user->save();
            }
            if($request->ajax()){
                return response()->json(['status' => 200, 'message' => "加急成功,您还剩余积分" . $user->{$feld} . "个!"]);
            }else{
                return back()->withInput()->with('info', "加急成功,您还剩余积分" . $user->{$feld} . "个!");
            }
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id, Request $request){
        $user = auth()->guard('company')->user();
        $companyBasic = CompanyBasic::where('uid', $user->uid)->orderBy('updatetime', 'desc')->first();
        $companyDepartment = CompanyDepartment::where('uid', $user->uid)->get();
        $companyJob = CompanyJob::where('uid', $user->uid)->where('id', $id)->first();
        //工作岗位转中文
        $companyJob->cn_jobsort .= $companyJob->job_category1 ? CollPosition::getPosName($companyJob->job_category1) : '';
        $companyJob->cn_jobsort .= $companyJob->job_category2 ? '+' . CollPosition::getPosName($companyJob->job_category2) : '';
        $companyJob->cn_jobsort .= $companyJob->job_category3 ? '+' . CollPosition::getPosName($companyJob->job_category3) : '';
        $companyJob->cn_jobsort .= $companyJob->job_category4 ? '+' . CollPosition::getPosName($companyJob->job_category4) : '';
        $companyJob->cn_jobsort .= $companyJob->job_category5 ? '+' . CollPosition::getPosName($companyJob->job_category5) : '';
        //工作地区转中文
        $companyJob->cn_workplace .= (strlen($companyJob->location1) == 8) ? '+' . CollTown::getTownName($companyJob->location1) : CollArea::getAreaName($companyJob->location1);
        $companyJob->cn_workplace .= (strlen($companyJob->location2) == 8) ? '+' . CollTown::getTownName($companyJob->location2) : CollArea::getAreaName($companyJob->location2);
        $companyJob->cn_workplace .= (strlen($companyJob->location3) == 8) ? '+' . CollTown::getTownName($companyJob->location3) : CollArea::getAreaName($companyJob->location3);
        $companyJob->cn_workplace .= (strlen($companyJob->location4) == 8) ? '+' . CollTown::getTownName($companyJob->location4) : CollArea::getAreaName($companyJob->location4);
        $companyJob->cn_workplace .= (strlen($companyJob->location5) == 8) ? '+' . CollTown::getTownName($companyJob->location5) : CollArea::getAreaName($companyJob->location5);
        $type = $request->type;
        $companyContact = CompanyContact::where('uid', $user->uid)->where('job_id', $companyJob->id)->first();

        return Style::view('company.jobEdit', compact('companyDepartment', 'companyJob', 'companyBasic', 'companyContact', 'type'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateJobRequest $request, $id){
        $user = auth()->guard('company')->user();
        $companyJob = CompanyJob::select('id')->where('uid', $user->uid)->where('id', $id)->first();
        if($companyJob->id){
            $input = $request->only('job_title', 'part_status', 'job_category1', 'job_category2', 'job_category3', 'job_category4', 'job_category5', 'industry', 'location1',
                'location2', 'location3', 'location4', 'location5', 'department', 'recruiting_num', 'salary_above', 'salary_below', 'description', 'education', 'work_year'
                , 'age_above', 'age_below', 'gender', 'language', 'welfare', 'contact_info');
            $input['updatetime'] = date('Y-m-d H:i:s', time());
            //审核状态设置
            switch(Site::get('job_review')){
                case  1:
                    $input['job_status'] = 1;
                    break;
                case  2:
                    $input['job_status'] = ($user->viptime >= date('Y-m-d H:i:s')) ? 1 : 0;
                    break;
                case  3:
                    $input['job_status'] = 0;
                    break;
                default:
                    $input['job_status'] = 0;
            }
            $input['xs_status'] = 0;
            CompanyJob::where('id', $id)->where('uid', $user->uid)->update($input);

            if($request->contact_info == 2){
                $companyContact = CompanyContact::where('uid', $user->uid)->where('job_id', $id)->first();
                $input = $request->only('contacts', 'mobile', 'phone', 'fax', 'email');
                if(!empty($companyContact->id)){
                    $input['updatetime'] = date('Y-m-d H:i:s', time());
                    CompanyContact::where('job_id', $id)->where('uid', $user->uid)->update($input);
                }else{
                    $input['job_id'] = $companyJob->id;
                    $input['uid'] = $user->uid;
                    $input['addtime'] = date('Y-m-d H:i:s', time());
                    $input['updatetime'] = date('Y-m-d H:i:s', time());
                    CompanyContact::create($input);
                }
            }
        }
        return redirect('company/jobadmin');
    }

    /**
     * 智能刷新
     * @param Request $request
     */
    function insertData($arr, $request){
        //插入数据库
        if(count($arr) > 0){
            $array = [];
            foreach($arr as $v){
                $array[] = [
                    'com_uid' => $request->com_uid,
                    'uptime' => $v,
                    'created_at' => date('Y-m-d H:i:s', time()),
                    'updated_at' => date('Y-m-d H:i:s', time())
                ];
            }
            DB::table('points')->insert($array);
        }
    }

    /**
     * 智能刷新
     * @param Request $request
     */
    function intelligent(Request $request){
        $number = !empty($request->days) ? $request->days * 3 * 5 : 0;//需要积分的数量
        //会员积分数量
        $userInfo = auth()->guard('company')->user();
        if(empty($userInfo)){
            return false;
        }
        $integralNumber = $userInfo->integralNumber();

        if($integralNumber > $number){
            //扣除积分数
            $userInfo->integralDeduct($number);
            //选择套餐的天数
            $days = $request->days;
            $hourly = [19, 15, 11, 7];
            $number = 3;
            $arr = [];
            $points = Points::where('com_uid', $request->com_uid)->orderBy('uptime', 'desc')->first();
            if(empty($points)){
                for($j = 0; $j < $days; $j++){
                    //当前天
                    if($j == 0){
                        //当前时间
                        $curr_time = date('Y-m-d ', time());
                        //当前的小时
                        $hour = date("G");
                        //当前以晚上19点为刷新时间
                        $curr_hour = 19;
                        if($hour >= 7 && $hour < $curr_hour){
                            $number = (integer)ceil(($curr_hour - $hour) / 4);
                        }else{
                            $number = 0;
                        }
                        if($number > 0){
                            for($i = $number - 1; $i >= 0; $i--){
                                if($i == ($number - 1)){
                                    $start_time = date('Y-m-d H:i:s', time());
                                }else{
                                    $start_time = $curr_time . $hourly[$i + 1] . ':00:00';
                                }
                                $end_time = $curr_time . $hourly[$i] . ':00:00';
                                $arr[] = rand_time($start_time, $end_time);
                            }
                        }
                    }else{
                        $number = 3;
                        //下一天
                        $curr_time = date("Y-m-d", strtotime("+" . $j . " day"));
                        for($i = $number - 1; $i >= 0; $i--){
                            $start_time = $curr_time . $hourly[$i + 1] . ':00:00';
                            $end_time = $curr_time . $hourly[$i] . ':00:00';
                            $arr[] = rand_time($start_time, $end_time);
                        }
                    }
                }
                //插入数据库
                $this->insertData($arr, $request);
            }else{
                $expireDate = substr($points->uptime, 0, 10);
                for($j = 0; $j < $days; $j++){
                    //原基础上下一天
                    $curr_time = date('Y-m-d', strtotime("+" . ($j + 1) . " day", strtotime($expireDate)));
                    for($i = $number - 1; $i >= 0; $i--){
                        $start_time = $curr_time . $hourly[$i + 1] . ':00:00';
                        $end_time = $curr_time . $hourly[$i] . ':00:00';
                        $arr[] = rand_time($start_time, $end_time);
                    }
                }
                //插入数据库
                $this->insertData($arr, $request);
            }
            return response()->json(['status' => 0, 'msg' => '职位智能自动刷新设置成功']);
        }else{
            return response()->json(['status' => 1, 'msg' => '设置失败，可能积分数不够，请先充值']);
        }
    }
}